// -----------------------------------------------------------------------
//  <copyright file="UserSeeder.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 20:07:08</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Exceptions;
using DaprPlus.Identity.Application;

using Liuliu.Fsb.Services.Identity.Domain.Entities;
using Liuliu.Fsb.Services.Identity.Domain.IntegrationEvents;

using Microsoft.AspNetCore.Identity;

using Microsoft.Extensions.DependencyInjection;


namespace Liuliu.Fsb.Services.Identity.Application.Identity.Users.Seeds;

public class UserSeeder(IServiceProvider provider) : EntitySeederBase<User>(provider)
{
    /// <summary>
    /// 重写以提供要初始化的种子数据
    /// </summary>
    /// <param name="scopedProvider"></param>
    /// <returns></returns>
    protected override Task<User[]> SeedDataAsync(IServiceProvider scopedProvider)
    {
        var list = new User[] { new() { UserName = "admin", NickName = "大站长", IsSystem = true } };
        return Task.FromResult(list);
    }

    protected override ISpecification<User> ExistingSpecification(User entity)
    {
        return new UserByNormalizedNameSpec<User>(entity.UserName.ToUpper());
    }

    protected override async Task SyncToDatabaseAsync(IServiceProvider scopedProvider, User[] entities)
    {
        if (entities.IsNullOrEmpty())
        {
            return;
        }

        var roleManager = scopedProvider.GetRequiredService<RoleManager<Role>>();
        var role = await roleManager.FindByNameAsync("系统管理员");
        var uow = scopedProvider.GetUnitOfWork(true);
        await uow.BeginOrUseTransactionAsync();
        var userManager = scopedProvider.GetRequiredService<UserManager<User>>();
        var addUsers = new List<UserRecord>();
        foreach (var entity in entities)
        {
            var user = await userManager.FindByNameAsync(entity.UserName);
            if (user != null)
            {
                continue;
            }

            entity.CreateUserExtend(null);
            var res = await userManager.CreateAsync(entity, "gmf31529019");
            if (!res.Succeeded)
            {
                throw new DaprPlusException($"UserSeeder Error: {res}");
            }
            if (role != null)
            {
                await userManager.AddToRoleAsync(entity, role.Name);
            }
            addUsers.Add(new UserRecord(entity.Id, entity.UserName, entity.NickName, entity.IsLocked));
        }

        if (addUsers.Count > 0)
        {
            uow.AddIntegrationEvent(new UserCreatedIntegrationEvent(addUsers.ToArray()));
        }

        await uow.CommitAsync();
    }
}
